package com.wcl.demo.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.wcl.demo.R;
import com.wcl.demo.db.NoteBgHelper;
import com.wcl.demo.model.entity.NoteBgData;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 15/11/26.
 */
public class PreviewPhotoActivity extends Activity implements View.OnClickListener {
    private ImageView preview_photo_Imv;
    private Bitmap bitmap;
    private TextView take_photo_retry_Btn, use_picture_Btn;
    private byte[] data;
    private String wayKey;
    private String time;//照片时间戳
    private String pictureKey;//图片索引,用于保存数据库,之后调取图片用(数据库)
    private NoteBgHelper noteBgHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview_photo);
        initView();
//        initData();
        data = getIntent().getByteArrayExtra("bitmap");
        wayKey=getIntent().getStringExtra("wayKey");
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

        bitmap = adjustPhotoRotation(bitmap, 90);
        Log.i("shaco", bitmap + "");
        preview_photo_Imv = (ImageView) findViewById(R.id.preview_photo_Imv);

        preview_photo_Imv.setImageBitmap(bitmap);


    }

    private void initView() {
        take_photo_retry_Btn = (TextView) findViewById(R.id.take_photo_retry_Btn);
        use_picture_Btn = (TextView) findViewById(R.id.use_picture_Btn);
        take_photo_retry_Btn.setOnClickListener(this);
        use_picture_Btn.setOnClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }
    //第一种旋转方式
//    Bitmap adjustPhotoRotation(Bitmap bm, final int orientationDegree)
//    {
//        Matrix m = new Matrix();
//        m.setRotate(orientationDegree, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
//
//        try {
//            Bitmap bm1 = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
//            return bm1;
//        } catch (OutOfMemoryError ex) {
//        }
//        return null;
//    }

    /**
     * 第二种旋转方式(旋转图片的方法)
     *
     * @param bm
     * @param orientationDegree
     * @return
     */
    Bitmap adjustPhotoRotation(Bitmap bm, final int orientationDegree) {

        Matrix m = new Matrix();
        m.setRotate(orientationDegree, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
        float targetX, targetY;
        if (orientationDegree == 90) {
            targetX = bm.getHeight();
            targetY = 0;
        } else {
            targetX = bm.getHeight();
            targetY = bm.getWidth();
        }

        final float[] values = new float[9];
        m.getValues(values);

        float x1 = values[Matrix.MTRANS_X];
        float y1 = values[Matrix.MTRANS_Y];

        m.postTranslate(targetX - x1, targetY - y1);

        Bitmap bm1 = Bitmap.createBitmap(bm.getHeight(), bm.getWidth(), Bitmap.Config.ARGB_8888);
        Paint paint = new Paint();
        Canvas canvas = new Canvas(bm1);
        canvas.drawBitmap(bm, m, paint);

        return bm1;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.take_photo_retry_Btn:
                Intent intent_back =new Intent(this, TakePhotoActivity.class);
                startActivity(intent_back);
                finish();
                break;

            case R.id.use_picture_Btn:
                if(wayKey==null){
                    Intent intent =new Intent(this, AroundActivity.class);
                    intent.putExtra("bitmap",data);
                    intent.putExtra("wayKey","0");
                    startActivity(intent);
                    finish();
                }else {
                    saveData();
                    pictureKey = "/storage/sdcard0/searchim/" + time;
                    addDB();

                    Intent intent = new Intent(this, NoteActivity.class);
                    startActivity(intent);
                    Toast.makeText(this, "更换成功", Toast.LENGTH_SHORT).show();
                    finish();
                }

                break;
        }
    }
    public void saveData() {
        String fileName = "sdcard/searchim/";
        time = String.valueOf(System.currentTimeMillis());
        File file = new File(fileName);
        if (!file.exists()) {
            file.mkdir();
        }
        savePicToSdcard(bitmap, fileName, time);

    }
    public static String savePicToSdcard(Bitmap bitmap, String path, String fileName) {
        String filePath = "";
        if (bitmap == null) {
            return filePath;
        } else {

            filePath = path + fileName;
            File destFile = new File(filePath);
            OutputStream os = null;
            try {
                os = new FileOutputStream(destFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                os.flush();
                os.close();
            } catch (IOException e) {
                filePath = "";
            }
        }
        return filePath;

    }
    public void addDB() {
        List<NoteBgData> list = new ArrayList<>();
        NoteBgData noteBgData = new NoteBgData();
        noteBgData.setPictureKey(pictureKey);
        list.add(noteBgData);
        noteBgHelper.saveBgInfor(list);
    }
}
